#pragma once

#include <PlatformApi/XPlatformApi.h>
#include <XBoostApi.h>
#include <boost/thread.hpp>
#include <boost/thread/shared_mutex.hpp>
#include <boost/atomic.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/unordered_set.hpp>
#include <boost/unordered_map.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/property_tree/ptree.hpp>  
#include <boost/property_tree/json_parser.hpp>  
#include <boost/property_tree/xml_parser.hpp>  

namespace XTrade {

	class MarketPlatform;

	const size_t EVT_PACKET = 100;

	class Msg
	{
	public:
		size_t peer;
		std::string req_data;
		std::string rsp_data;
	};

	class MarketThread : public XThreadSpi
	{
	private:
		MarketPlatform* platform_;
	public:
		MarketThread();

		virtual int on_run(bool is_join);
		virtual int on_cmd(int cmd, void* param);
	};

	class MarketPlatform 
		: public XPlatformSpi
		, public XIndicatorQuoteProvider
		, public XIndicatorTradeProvider
	{
	public:
		MarketPlatform();
		~MarketPlatform();

		bool start(boost::property_tree::ptree &cfg);
		void stop();

		void run();

		void post_request(std::shared_ptr<Msg>& msg);
		bool pop_request(std::shared_ptr<Msg>& msg);
		void post_response(std::shared_ptr<Msg>& msg);
		bool pop_response(std::shared_ptr<Msg>& msg);

		XThreadApi* select_thread();

		virtual int on_run(bool is_join);
		virtual int on_run_thread();
	private:
		XPlatformApi* api_;
		XBoost::EvtThread evt_thread_;
		struct XThreadInfo
		{
			std::string name;
			XThreadApi* api;
		};
		std::map<std::string, std::shared_ptr<XThreadInfo>> thread_map_;
		std::map<std::string, std::shared_ptr<XThreadInfo>>::iterator thread_it_;
		boost::mutex thread_mutex_;
		XBoost::BlockingQueue<std::shared_ptr<Msg>> req_que_;
		XBoost::BlockingQueue<std::shared_ptr<Msg>> rsp_que_;
	};
}
